package com.limao.Admin.Servlet;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.limao.Model.LzPluginException;
import com.limao.Tool.CacheClass;
import com.limao.Tool.Function;
import com.limao.Utils.OSSObjectSample;

/**
 * 实现广告上传图片
 * @author LeiFulin
 *
 * @date 2014-10-11
 */
@WebServlet(name="FileUpload", urlPatterns="/admin/FileUpload",asyncSupported=false)
public class FileUpload extends HttpServlet {

	private static final long serialVersionUID = 2175896310613494505L;
	
	private static String[] FilTpye = { "jpg", "jpeg", "png", "amr" };
	private static long MaxFileSize = 1024 * 1024 * 1;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		String formName = request.getParameter("formName");
		String imgID = request.getParameter("imgID");
		String imageNmae = request.getParameter("imageNmae");
		//response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		System.out.println("FileUploadServlet: "+formName+"  "+imgID+" "+imageNmae);
	
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(request);
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField()) {
					System.out.println("表单参数名:" + item.getFieldName() + "，表单参数值:" + item.getString("UTF-8"));
				} else { 
					String errMessage = "";
					String extName = ""; //保存文件扩展名
					
					String contentType = item.getContentType();
					System.out.println("contentType:"+contentType.toString());
					System.out.println("上传文件的大小:" + item.getSize());
					System.out.println("上传文件的类型:" + item.getContentType());
					// 注意item.getName(),会返回上载文件在客户端的完整路径名称
					System.out.println("上传文件的名称:" + item.getName());
					
					String filename = item.getName();

					int index = filename.lastIndexOf("\\");
					if (index != -1)
						filename = filename.substring(index + 1);
					if (!FileType(filename, item.getSize()))// 上传的文件类型与大小										// 检测
					{
						throw new LzPluginException("文件类型不对或文件超过1M ");
					}
					else
					{
						// 向服务器写出文件
						String dd=null;
						InputStream in = null;
						try {
							in = item.getInputStream();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						
						if(CacheClass.isOut==0)//外网图片上传
						{
							String newFileNmae=hashNewFile(item.getName());
							boolean falg;
							try {
								//外网上传图片
						    falg =	OSSObjectSample.OSS_upload(in, newFileNmae, item.getSize(), item.getContentType());
						    
						    if(falg){
						    	dd=newFileNmae;
						    	System.out.println("文件名：" + newFileNmae);
						    }
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								dd=null;
					        } finally 
					        {
					        	if (in != null)
									try {
										in.close();
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
					        }
							
							if(dd==null)
					        {
					            request.setCharacterEncoding("UTF-8");
					            response.setContentType("text/html");
					            response.setCharacterEncoding("UTF-8");
					        	PrintWriter out =  new PrintWriter(response.getOutputStream());
					        	errMessage = "上传出错。。！";
								out.println("<script charset=\"utf-8\">alert('" + errMessage + "');</script>" + 
							              "<font color=red size=5>fail</font>&nbsp;&nbsp;&nbsp;<a href=upload.jsp?formName="+formName+"&imgID="+imgID+"&imageNmae="+imageNmae+" size=5>upload.....</a>");
								out.flush();
								out.close();
					        }
					        else
					        {     request.setCharacterEncoding("UTF-8");
					              response.setContentType("text/html");
					              response.setCharacterEncoding("UTF-8");
					        	PrintWriter out =  new PrintWriter(response.getOutputStream());
								out.println("<script charset=\"utf-8\" >alert(\"success.....\");" + 
										  	  "parent.document." + formName + "."+imgID+".src=encodeURI('"+CacheClass.getImgUrl()+ dd + "');" +
										  	  "parent.document." + formName + "."+imgID+".style.display='';" + 
								              "parent.document." + formName + "."+imageNmae+".value = '" + dd + "';" +
								              "parent.document." + formName + ".submit.disabled = false;</script>" +
								            "<font color=red size=5>success</font>&nbsp;&nbsp;&nbsp;<a href=upload.jsp?formName="+formName+"&imgID="+imgID+"&imageNmae="+imageNmae+" size=5>upload...</a>"            
								);
								out.flush();
								out.close();
					        }
							
						} else	if(CacheClass.isOut==1)//外网测试图片上传
						{
							String newFileNmae=hashNewFile(item.getName());
							boolean falg;
							try {
								//外网上传图片
						    falg =	OSSObjectSample.OSS_upload(in, newFileNmae, item.getSize(), item.getContentType());
						    
						    if(falg){
						    	dd=newFileNmae;
						    	System.out.println("文件名：" + newFileNmae);
						    }
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								dd=null;
					        } finally 
					        {
					        	if (in != null)
									try {
										in.close();
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
					        }
							
							if(dd==null)
					        {
					            request.setCharacterEncoding("UTF-8");
					            response.setContentType("text/html");
					            response.setCharacterEncoding("UTF-8");
					        	PrintWriter out =  new PrintWriter(response.getOutputStream());
					        	errMessage = "上传出错。。！";
								out.println("<script charset=\"utf-8\">alert('" + errMessage + "');</script>" + 
							              "<font color=red size=5>fail</font>&nbsp;&nbsp;&nbsp;<a href=upload.jsp?formName="+formName+"&imgID="+imgID+"&imageNmae="+imageNmae+" size=5>upload.....</a>");
								out.flush();
								out.close();
					        }
					        else
					        {     request.setCharacterEncoding("UTF-8");
					              response.setContentType("text/html");
					              response.setCharacterEncoding("UTF-8");
					        	PrintWriter out =  new PrintWriter(response.getOutputStream());
								out.println("<script charset=\"utf-8\" >alert(\"success.....\");" + 
										  	  "parent.document." + formName + "."+imgID+".src=encodeURI('"+CacheClass.getImgUrl()+ dd + "');" +
										  	  "parent.document." + formName + "."+imgID+".style.display='';" + 
								              "parent.document." + formName + "."+imageNmae+".value = '" + dd + "';" +
								              "parent.document." + formName + ".submit.disabled = false;</script>" +
								            "<font color=red size=5>success</font>&nbsp;&nbsp;&nbsp;<a href=upload.jsp?formName="+formName+"&imgID="+imgID+"&imageNmae="+imageNmae+" size=5>upload...</a>"            
								);
								out.flush();
								out.close();
					        }
							
						}
						else
						{   //内网上传的图片
							// 新的，下2行
							
							String dir=new File(System.getProperty("catalina.home")).toString()+File.separator+"webapps"+File.separator+Function.myFiles+File.separator+"faceImage";
							System.out.println("dir:"+dir);
							//创建文件目录
							File filedir = new File(dir);
							System.out.println("filedir:"+filedir);
							 if (!filedir.exists())
									filedir.mkdir();
							 filename=hashNewFile(item.getName());
							System.out.println("newFileNmae:"+filename);
							//实现上传
							File file = new File(dir ,filename);
							if(file.exists()) errMessage = "该文件名称已经存在！";
							request.setCharacterEncoding("UTF-8");
						    response.setContentType("text/html");
						    response.setCharacterEncoding("UTF-8");
							PrintWriter out =  new PrintWriter(response.getOutputStream());
							if(!errMessage.equals(""))
							{
								out.println("<script charset=\"utf-8\">alert('" + errMessage + "');</script>" + 
							              "<font color=red size=5>fail</font>&nbsp;&nbsp;&nbsp;<a href=upload.jsp?formName="+formName+"&imgID="+imgID+"&imageNmae="+imageNmae+" size=5>upload.....</a>");
								out.flush();
								out.close();
							}
							else
							{
								item.write(file); 
								String baseUrlIn=CacheClass.getImgUrl();
								String RelativeURL =Function.myFiles+"/faceImage/" + filename; 
								String absoluteURL =baseUrlIn+RelativeURL; 
								System.out.println("absoluteURL:"+absoluteURL);
								out.println("<script charset=\"utf-8\" >alert(\"success.....\");" + 
										  	  "parent.document." + formName + "."+imgID+".src=encodeURI('" + absoluteURL + "');" +
										  	  "parent.document." + formName + "."+imgID+".style.display='';" + 
								              "parent.document." + formName + "."+imageNmae+".value = '" + RelativeURL + "';" +
								              "parent.document." + formName + ".submit.disabled = false;</script>" +
								            "<font color=red size=5>success</font>&nbsp;&nbsp;&nbsp;<a href=upload.jsp?formName="+formName+"&imgID="+imgID+"&imageNmae="+imageNmae+" size=5>upload...</a>"            
								);
								out.flush();
								out.close();
							}
							
						}
						
					}
					
				} 
			}
		} catch (Exception e) {
			 e.printStackTrace();
		}
	}
	// 生成唯一性名称的文件名
	private static String uuidName(String fileName) {
		UUID uuid = UUID.randomUUID();
		fileName = fileName.substring((fileName.lastIndexOf(".")));
		return uuid.toString() + "_" + fileName;
	}
	
	public static String hashNewFile(String fileName){
		int hashCode = fileName.hashCode();
		return hashCode+uuidName(fileName);
	}
	
	private static boolean FileType(String filename, long size) {
		boolean tmp = false;
		if (size > MaxFileSize)
			return tmp;
		String extraFile = filename.substring((filename.lastIndexOf(".") + 1));
		for (int i = 0; i < FilTpye.length; i++) {
			if (extraFile.equalsIgnoreCase(FilTpye[i])) {
				tmp = true;
				break;
			}
		}
		return tmp;
	}

}
